﻿///
///数据加载器，加载接口数据，自动填写到具体的页面
///
(function ($) {
    $.fn.loaderHandler = function () {
        var $this = this;
        if ($this.data('loaderHandler')) {
            return $this.data('loaderHandler');
        }

        $this.data('loaderHandler', this);
        //初始化
        $this.initialize = function (options) {
            var defoption = {
                beforeHandleResult: function (result, totalCount, container) {
                },
                afterHandleResult: function (result, totalCount, container) {
                },
                command: '',
                parameter: {}
            };
            $this.options = $.extend({}, defoption, options);

        }

        //加载数据
        $this.load = function () {
            var param = $this.options.parameter;
            //调用接口
            $this.executeCommand({ successCallBack: function (result, totalCount) {
                $this.loaderresult = result;
                $this.options.beforeHandleResult(result, totalCount, $this);

                //处理属性绑定
                _innerBind(result, '');

                $this.options.afterHandleResult(result, totalCount, $this);
            }
            }, $this.options.command, param);
        }
        //支持对象嵌套属性方式进行绑定
        _innerBind = function (val, boundKey) {
            //            if (!val) {
            //                return;
            //            }
            if (val instanceof Object) {
                for (var prop in val) {
                    var key = '';
                    if (boundKey == '') {
                        key = prop;
                    } else {
                        key = boundKey + '\\.' + prop;
                    }
                    _innerBind(val[prop], key);
                }
            } else {
                //触发值变更事件
                var result = $this.find("[prop=" + boundKey + "]").triggerHandler('valuechange', { handler: $this, value: val });
                if (result != false) {
                    //目前只支持设置html属性
                    $this.find("[prop=" + boundKey + "]").html(val);
                    //触发值变更事件
                    $this.find("[prop=" + boundKey + "]").triggerHandler('valuechanged', { handler: $this, value: val });
                }
            }
        }

        return $this;
    }
})(jQuery);